#include "ConcurrentAlloc.h"
#include <thread>
#include <iostream>

void Alloc1()
{
	for (int i = 0; i < 5; ++i)
	{
		void* ptr = concurrentAlloc(6);
	}
}

void Alloc2()
{
	for (int i = 0; i < 5; ++i)
	{
		void* ptr = concurrentAlloc(7);
	}
}

void TLSTest()
{
	std::thread t1(Alloc1);
	std::thread t2(Alloc2);

	t1.join();
	t2.join();
}

//----------------------

void testConcurrentAlloc1()
{
	void* p1 = concurrentAlloc(1);
	void* p2 = concurrentAlloc(2);
	void* p3 = concurrentAlloc(3);
	void* p4 = concurrentAlloc(4);
	void* p5 = concurrentAlloc(5);

	std::cout << p1 << std::endl;
	std::cout << p2 << std::endl;
	std::cout << p3 << std::endl;
	std::cout << p4 << std::endl;
	std::cout << p5 << std::endl;

	concurrentDealloc(p1);
	concurrentDealloc(p2);
	concurrentDealloc(p3);
	concurrentDealloc(p4);
	concurrentDealloc(p5);
}

//--------------------

void testConcurrentAlloc2()
{
	for (int i = 0; i < 1024; ++i)
	{
		void* p1 = concurrentAlloc(6);

		if (i == 1022)
		{
			int x = 0;
		}
	}

	void* p1 = concurrentAlloc(8);
	std::cout << p1 << std::endl;
}

//-------------------------

void testAddressShift()
{
	PAGE_ID id1 = 2000;
	PAGE_ID id2 = 2001;
	char* p1 = (char*)(id1 << PAGE_SHIFT);
	char* p2 = (char*)(id2 << PAGE_SHIFT);
	//std::cout << p1 << std::endl;
	//std::cout << p2 << std::endl;

	while (p1 < p2)
	{
		std::cout << (void*)p1 << ":" << ((PAGE_ID)p1 >> PAGE_SHIFT) << std::endl;
		p1 += 8;
	}

}

//-----------------------

void MultiThreadAlloc1()
{
	std::vector<void*> v;
	for (int i = 0; i < 1; ++i)
	{
		void* ptr = concurrentAlloc(6);
		v.push_back(ptr);
	}

	for (auto e : v)
	{
		concurrentDealloc(e);
	}
}

void MultiThreadAlloc2()
{
	std::vector<void*> v;
	for (int i = 0; i < 1; ++i)
	{
		void* ptr = concurrentAlloc(7);
		v.push_back(ptr);
	}

	for (auto e : v)
	{
		concurrentDealloc(e);
	}
}

void TestMultiThread()
{
	std::thread t1(MultiThreadAlloc1);
	std::thread t2(MultiThreadAlloc2);

	t1.join();
	t2.join();
}

void BigAlloc()
{
	void* p1 = concurrentAlloc(257 * 1024);
	concurrentDealloc(p1);

	void* p2 = concurrentAlloc(129 * 8 * 1024);
	concurrentDealloc(p2);
}

//int main()
//{
//	//TLSTest();
//	//testConcurrentAlloc1();
//	//testConcurrentAlloc2();
//	//testAddressShift();
//	//TestMultiThread();
//
//	//BigAlloc();
//
//
//	return 0;
//}

//int main()
//{
//	void* ptr1 = systemAlloc(1);
//	void* ptr2 = systemAlloc(2);
//	void* ptr3 = systemAlloc(3);
//
//	std::cout << ptr1 << std::endl;
//	std::cout << ptr2 << std::endl;
//	std::cout << ptr3 << std::endl;
//
//	return 0;
//}

